package com.zm.tools.util.core;

import com.alibaba.fastjson.JSONObject;
import com.zm.tools.util.exception.ExcelUtilException;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zoum
 * @create 2018/6/7 14:55
 */
public class ExcelUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);


    /**
     * @param headers 头名称数组 （决定了有多少列），每一个头名称对应业务参数里这一列的键
     *                 如：["name-姓名", "age-年龄", "gender-性别"]
     * @param businessParams 业务参数列表 （决定了有多少行）
     *                 如：[{"name":"zm", "age":"28", "gender":"male"},{"name":"zm", "age":"28", "gender":"male"}]
     * @return
     */
    public static HSSFWorkbook export(String [] headers, List<JSONObject> businessParams) throws ExcelUtilException{
        LOGGER.info("export|start|headers = {}, businessParams = {}", JSONObject.toJSON(headers), JSONObject.toJSONString(businessParams));
        if (headers == null){
            throw new ExcelUtilException("headers must not null.");
        }
        HSSFWorkbook hwb = new HSSFWorkbook();
        HSSFSheet sheet = hwb.createSheet();

        int rowIndex = 0;
        Row headerRow = sheet.createRow(rowIndex++);

        //设置表头
        for (int hIndex = 0; hIndex < headers.length ; hIndex++){
            String header = headers[hIndex];
            if (header == null){
                headerRow.createCell(hIndex).setCellValue("");
            }else {
                String []headerAry = header.split("-");
                headerRow.createCell(hIndex).setCellValue(headerAry.length == 2 ? headerAry[1] : headerAry[0]);
            }
        }

        //设置内容
        for (JSONObject o: businessParams) {
            HSSFRow row = sheet.createRow(rowIndex++);

            final AtomicInteger cellIndex = new AtomicInteger(0);
            for (String header : headers){
                if (header == null){
                    row.createCell(cellIndex.getAndIncrement()).setCellValue("")
                    ;
                }else {
                    String []headerAry = header.split("-");
                    row.createCell(cellIndex.getAndIncrement()).setCellValue(o.getString(headerAry.length > 0 ? headerAry[0] : ""));
                }
            }

        }
        LOGGER.info("export|end");
        return hwb;
    }

    /**
     * 导出文件到指定位置
     * @param headers 头信息
     * @param businessParams 行信息
     * @param filePath 文件路径
     * @throws ExcelUtilException
     */
    public static void export(String [] headers, List<JSONObject> businessParams, String filePath) throws ExcelUtilException{
        try (HSSFWorkbook hwb = export(headers, businessParams);
            OutputStream outputStream = new FileOutputStream(filePath)){
            hwb.write(outputStream);
            outputStream.flush();
        } catch (FileNotFoundException fe){
            throw new ExcelUtilException("export file error.", fe);
        } catch (IOException ie ){
            throw new ExcelUtilException("export file error.", ie);
        }
    }
}
